<template>
  <div>
    <div class="doumee-filter">
      <el-form inline label-suffix="：" @submit.native.prevent>
        <el-form-item :label="$t('message.famc')">
          <el-input v-model="filters.planName" :placeholder="$t('message.qsr') + $t('message.famc')" clearable />
        </el-form-item>
        <el-form-item>
          <el-button v-preventReClick type="primary" @click="getList(1)">{{ $t('message.cz') }}</el-button>
          <el-button v-preventReClick @click="clearFilter">{{ $t('message.clear') }}</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div v-if="meta.indexOf('VenuePriceEdit') > -1" class="doumee-table-buttons">
      <el-button type="primary" @click="toAddEditPricePlan(0)">{{ $t('message.add') }}</el-button>
    </div>
    <el-table
      ref="table"
      :data="list"
      element-loading-text="Loading"
      border
      fit
      :header-row-class-name="'table-header'"
      class="doumee-element-table"
    >
      <el-table-column
        align="center"
        :label="$t('message.famc')"
        prop="planName"
        min-width="200"
        sortable
      />
      <el-table-column align="center" :label="$t('message.sfqy')" min-width="140">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.status"
            :active-value="'1'"
            :inactive-value="'0'"
            :disabled="scope.row.status === '1'"
            @change="setPlanStatus($event, scope.row.id, scope.$index)"
          />
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        :label="$t('message.sort')"
        prop="sort"
        min-width="140"
      />
      <el-table-column
        align="center"
        :label="$t('message.scxgsj')"
        prop="editTime"
        min-width="200"
      />
      <el-table-column
        :label="$t('message.caozuo')"
        min-width="300"
        align="center"
        fixed="right"
      >
        <template slot-scope="scope">
          <div class="flex-cc">
            <el-button v-if="meta.indexOf('VenuePriceEdit') > -1" v-preventReClick type="text" @click="toAddEditPricePlan(1, scope.row)">{{ $t('message.edit') }}</el-button>
            <el-button v-if="meta.indexOf('VenuePriceEdit') > -1" v-preventReClick type="text" @click="toCopyPricePlan(scope.row.id)">{{ $t('message.fzfa') }}</el-button>
            <el-button v-if="meta.indexOf('VenuePriceEdit') > -1" v-preventReClick :disabled="scope.row.status === '1'" type="text" class="secondColor" @click="toDeletePricePlan(scope.row.id)">{{ $t('message.del') }}</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <Paginations
      :total="total"
      :page="pagination.page"
      @current-change="getList"
      @SizeChange="handleSizeChange"
    />

    <el-dialog
      :title="dialogType ? $t('message.bjdjfa') : $t('message.xzdjfa')"
      :close-on-click-modal="modalDialog"
      :close-on-press-escape="modalDialog"
      :visible.sync="showAddPricePlan"
    >
      <el-form ref="ruleForm" label-width="auto" :rules="rules" :model="addEditPricePlanForm" label-suffix="：">
        <el-form-item :label="$t('message.famc')" prop="planName">
          <el-input
            v-model="addEditPricePlanForm.planName"
            :placeholder="$t('message.qsr') + $t('message.famc')"
          />
        </el-form-item>
        <el-form-item :label="$t('message.sort')" prop="sort">
          <el-input
            v-model="addEditPricePlanForm.sort"
            :placeholder="$t('message.qsr') + $t('message.sort')"
          />
        </el-form-item>
        <el-form-item :label="$t('message.sfqy')">
          <el-switch
            v-model="addEditPricePlanForm.status"
            :active-value="'1'"
            :inactive-value="'0'"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelAddEditPricePlan">{{ $t('message.qx') }}</el-button>
        <el-button
          v-preventReClick
          :loading="subLoading"
          type="primary"
          @click="submitForm('ruleForm')"
        >{{ $t('message.qr') }}</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="$t('message.fzdjfa')" :visible.sync="showCopyPricePlan" :close-on-click-modal="modalDialog" :close-on-press-escape="modalDialog">
      <el-form ref="copeForm" label-width="auto" :rules="rules" :model="copyPricePlanForm" label-suffix="：">
        <el-form-item :label="$t('message.famc')" prop="planName">
          <el-input
            v-model="copyPricePlanForm.planName"
            :placeholder="$t('message.qsr') + $t('message.famc')"
          />
        </el-form-item>
        <el-form-item :label="$t('message.sort')" prop="sort">
          <el-input v-model="copyPricePlanForm.sort" :placeholder="$t('message.qsr') + $t('message.sort')" />
        </el-form-item>
        <el-form-item :label="$t('message.sfqy')">
          <el-switch
            v-model="copyPricePlanForm.status"
            :active-value="'1'"
            :inactive-value="'0'"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelCopyPricePlan">{{ $t('message.qx') }}</el-button>
        <el-button v-preventReClick type="primary" @click="submitForm('copeForm')">{{ $t('message.qr') }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  sitePriceList,
  sitePriceAdd,
  sitePriceEdit,
  sitePriceDelete,
  setSitePricePlanStatus,
  sitePriceCopy
} from '@/api'
import { parseTime } from '@/utils'
import store from '@/store'
export default {
  name: 'PriceOptions',
  data() {
    return {
      modalDialog: store.getters.dialog,
      subLoading: false,
      list: [],
      total: 0,
      filters: {
        planName: ''
      },
      dialogType: 0,
      activeEditPlanIndex: '',
      showAddPricePlan: false,
      copyPricePlanForm: {
        planId: '',
        planName: '',
        sort: '',
        status: '0'
      },
      showCopyPricePlan: false,
      addEditPricePlanForm: {
        planName: '',
        sort: '',
        status: '0'
      },
      pagination: {
        page: 1,
        rows: 10
      },
      meta: [],
      rules: {
        planName: [{ required: true, message: this.$t('message.qsr') + this.$t('message.famc'), trigger: 'blur' }],
        sort: [{ required: true, message: this.$t('message.qsr') + this.$t('message.sort'), trigger: 'blur' }]
      }
    }
  },
  created() {
    this.meta = this.$route.meta.buttons || []
    this.getList(1)
    this.$refs.table.doLayout()
  },
  methods: {
    handleSizeChange(value) {
      this.pagination.rows = value
      this.getList(1)
    },
    submitForm(formName) {
      const that = this
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.subLoading = true
          if (formName === 'ruleForm') {
            that.cofirmAddEditPricePlan()
          } else {
            that.cofirmCopyPricePlan()
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 获取方案列表
    getList(page) {
      const { filters, pagination } = this
      if (page) {
        pagination.page = page
        this.pagination.page = Number(page)
      }
      pagination.firstQueryTime = parseTime(new Date())
      this.listLoading = true
      sitePriceList({
        pagination,
        param: {
          ...filters,
          venueId: sessionStorage.getItem('venueId')
        }
      })
        .then((res) => {
          this.listLoading = false
          if (res.errorCode === '000000') {
            this.list = res.recordList
            this.total = res.totalCount
            if (res.totalCount && res.recordList.length === 0 && pagination.page > 1) {
              this.getList(Math.ceil(res.totalCount / pagination.rows))
            }
          }
        })
        .catch(() => {
          this.listLoading = false
        })
    },
    // 清空筛选项
    clearFilter() {
      this.filters = {}
      this.getList(1)
    },
    // 设置方案启用/禁用
    setPlanStatus(status, planId, index) {
      setSitePricePlanStatus({ param: { status, planId }})
        .then((res) => {
          if (res.errorCode !== '000000') return
          const { list } = this
          for (let i = 0; i < list.length; i++) {
            if (list[i].id !== planId && list[i].status === '1') {
              this.$set(this.list[i], 'status', '0')
            }
          }
        })
        .catch(() => {
          this.$set(this.list[index], 'status', status === '0' ? '1' : '0')
        })
    },
    // 新增/编辑定价方案
    toAddEditPricePlan(dialogType, row) {
      if (dialogType) {
        row = JSON.stringify(row)
        this.addEditPricePlanForm = JSON.parse(row)
      } else {
        this.addEditPricePlanForm = {
          planName: '',
          sort: '',
          status: '0'
        }
      }
      this.showAddPricePlan = true
      this.dialogType = dialogType
    },
    // 确认新增/编辑定价方案
    cofirmAddEditPricePlan() {
      const { dialogType, addEditPricePlanForm: param } = this
      if (dialogType) {
        // 编辑
        param.planId = param.id
        sitePriceEdit({ param }).then((res) => {
          this.subLoading = false
          if (res.errorCode === '000000') {
            this.$message.success(this.$t('message.xgcg'))
            this.showAddPricePlan = false
            this.getList()
          }
        }).catch(() => {
          this.subLoading = false
        })
      } else {
        // 新增
        param.venueId = sessionStorage.getItem('venueId')
        sitePriceAdd({ param }).then((res) => {
          this.subLoading = false
          if (res.errorCode === '000000') {
            this.$message.success(this.$t('message.addcg'))
            this.showAddPricePlan = false
            this.getList()
          }
        }).catch(() => {
          this.subLoading = false
        })
      }
    },
    // 取消新增/编辑定价方案
    cancelAddEditPricePlan() {
      this.showAddPricePlan = false
      this.addEditPricePlanForm = {
        planName: '',
        sort: '',
        status: '0'
      }
    },
    // 删除定价方案
    toDeletePricePlan(planId) {
      this.$confirm(this.$t('message.scfatc'), this.$t('message.ts'), {
        confirmButtonText: this.$t('message.qd'),
        cancelButtonText: this.$t('message.qx'),
        type: 'warning'
      })
        .then(() => {
          sitePriceDelete({ param: { planId }}).then((res) => {
            if (res.errorCode === '000000') {
              this.$message.success(this.$t('message.delcg'))
              this.getList()
            }
          })
        })
        .catch(() => {
          // console.log('已取消删除')
        })
    },
    // 复制方案
    toCopyPricePlan(id) {
      this.showCopyPricePlan = true
      this.copyPricePlanForm.planId = id
    },
    // 取消复制方案
    cancelCopyPricePlan() {
      this.showCopyPricePlan = false
    },
    // 确认复制方案
    cofirmCopyPricePlan() {
      const { copyPricePlanForm: param } = this
      sitePriceCopy({ param }).then((res) => {
        this.subLoading = false
        if (res.errorCode === '000000') {
          this.$message.success(this.$t('message.fzcg'))
          this.showCopyPricePlan = false
          this.getList()
        }
      }).catch(() => {
        this.subLoading = false
      })
    }
  }
}
</script>
